package com.jdd.modules.parking.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jdd.common.api.vo.Result;
import com.jdd.common.constant.JddConstant;
import com.jdd.common.system.vo.LoginUser;
import com.jdd.common.util.LoginUserUtils;
import com.jdd.modules.area.entity.ParkAreaInfo;
import com.jdd.modules.area.mapper.ParkAreaInfoMapper;
import com.jdd.modules.operationLog.entity.ParkHandOverLog;
import com.jdd.modules.operationLog.mapper.ParkHandOverLogMapper;
import com.jdd.modules.parking.entity.ConfigParkInfo;
import com.jdd.modules.parking.entity.ParkArmInfo;
import com.jdd.modules.parking.entity.ParkWorkStation;
import com.jdd.modules.parking.mapper.ConfigParkInfoMapper;
import com.jdd.modules.parking.mapper.ParkWorkStationMapper;
import com.jdd.modules.parking.service.IParkArmInfoService;
import com.jdd.modules.parking.service.IParkWorkStationService;
import com.jdd.modules.parking.vo.ParkWorkStationVo;
import com.jdd.modules.system.entity.SysUser;
import com.jdd.modules.system.mapper.SysUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 工作站
 * @Author: jdd
 * @Date: 2021-11-05
 * @Version: V1.0
 */
@Service
@Slf4j
public class ParkWorkStationServiceImpl extends ServiceImpl<ParkWorkStationMapper, ParkWorkStation> implements IParkWorkStationService {

    @Resource
    private ConfigParkInfoMapper configParkInfoMapper;
    @Resource
    private IParkArmInfoService parkArmInfoService;
    @Resource
    private ParkAreaInfoMapper parkAreaInfoMapper;
    @Resource
    private ParkHandOverLogMapper parkHandOverLogMapper;
    @Resource
    private SysUserMapper sysUserMapper;
    @Value("${parkInfo.parkCode}")
    private String parkCode;

    /**
     * 添加工作站
     *
     * @param parkWorkStationVo 工作站VO
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveWorkStationFrom(ParkWorkStationVo parkWorkStationVo) throws Exception {
        //车场配置
        ConfigParkInfo config = getConfig();
        if (ObjectUtil.isEmpty(config)) {
            log.error("---------saveWorkStationFrom提示找不到车场配置！！！------------");
            return false;
        }
        //新增前判断工作站是否重名，不能重名
        QueryWrapper<ParkWorkStation> wrapper = new QueryWrapper<>();
        wrapper.eq("work_name", parkWorkStationVo.getWorkName());
        List<ParkWorkStation> workStations = list(wrapper);
        if (workStations != null && workStations.size() > 0) {
            log.error("---------saveWorkStationFrom提示有重名工作站------------");
            return false;
        }
        if (parkWorkStationVo.getParkArmList() != null && parkWorkStationVo.getParkArmList().size() > 0) {
            List<String> parkArmList = parkWorkStationVo.getParkArmList();
            for (String id : parkArmList) {
                ParkArmInfo parkArmInfo = parkArmInfoService.getById(id);
                if (ObjectUtil.isNotEmpty(parkArmInfo) && ObjectUtil.isNotEmpty(parkArmInfo.getWorkStationId())) {
                    //表明该车道提前被别人选了
                    log.error("------saveWorkStationFrom提示选择的车道被别人先选了");
                    return false;
                }
            }
        }
        //添加工作站站
        ParkWorkStation parkWorkStation = new ParkWorkStation();
        BeanUtils.copyProperties(parkWorkStationVo, parkWorkStation);
        parkWorkStation.setParkName(config.getParkName());
        parkWorkStation.setParkCode(config.getParkCode());
        parkWorkStation.setCreateTime(new Date());
        //新增时离线
        parkWorkStation.setStatus(JddConstant.StringNumber.STRING_ZERO);
        //添加工作站
        if (!save(parkWorkStation)) {
            log.error("-----------saveWorkStationFrom提示工作站保存失败--------------------");
        }
        //批量给车道设置工作站
        //如果车道更新失败就回滚工作站的添加
        if (!updateArms(parkWorkStationVo, parkWorkStation, "")) {
            log.error("-----------saveWorkStationFrom提示车道更新失败--------------------");
            throw new Exception("saveWorkStationFrom提示车道更新失败");
        }
        return true;
    }

    /**
     * 编辑工作站
     *
     * @param parkWorkStationVo 工作站VO
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateWorkStationFrom(ParkWorkStationVo parkWorkStationVo) throws Exception {
        if (ObjectUtil.isEmpty(parkWorkStationVo.getId())) {
            log.error("-----updateWorkStationFrom提示参数id为空----");
            return false;
        }
        ParkWorkStation workStation = this.getById(parkWorkStationVo.getId());
        if (ObjectUtil.isEmpty(workStation)) {
            log.error("----------updateWorkStationFrom提示工作站不存在----------");
            return false;
        }
        //状态如果是在线的就不能更改
        if (JddConstant.StringNumber.STRING_ONE.equals(workStation.getStatus())) {
            log.error("------------updateWorkStationFrom提示该工作站在线，无法修改----------");
            return false;
        }
        if (parkWorkStationVo.getParkArmList() != null && parkWorkStationVo.getParkArmList().size() > 0) {
            List<String> parkArmList = parkWorkStationVo.getParkArmList();
            for (String id : parkArmList) {
                ParkArmInfo parkArmInfo = parkArmInfoService.getById(id);
                //修改时，车道要么等于当前工作站id，要么为空
                //如果选择的车道的工作站id不是当前工作站id，并且车道有别的工作站的id，说明车道被别人选了
                if (ObjectUtil.isNotEmpty(parkArmInfo) && ObjectUtil.isNotEmpty(parkArmInfo.getWorkStationId()) && !workStation.getId().equals(parkArmInfo.getWorkStationId())) {
                    //表明该车道提前被别人选了
                    log.error("------saveWorkStationFrom提示选择的车道被别人先选了");
                    return false;
                }
            }
        }
        //如果工作站改名字了，交接班以往记录也改名
        if (!parkWorkStationVo.getWorkName().equals(workStation.getWorkName())) {
            //交接班记录的工作站名字也改名
            QueryWrapper<ParkHandOverLog> handOverLogQueryWrapper = new QueryWrapper<>();
            handOverLogQueryWrapper.eq("work_name", workStation.getWorkName());
            List<ParkHandOverLog> parkHandOverLogs = parkHandOverLogMapper.selectList(handOverLogQueryWrapper);
            if (parkHandOverLogs != null && parkHandOverLogs.size() > 0) {
                ParkHandOverLog parkHandOverLog = new ParkHandOverLog();
                parkHandOverLog.setWorkName(parkWorkStationVo.getWorkName());
                parkHandOverLog.setSynchronousStatus("N");
                UpdateWrapper<ParkHandOverLog> wrapper = new UpdateWrapper<>();
                wrapper.eq("work_name", workStation.getWorkName());
                if (parkHandOverLogMapper.update(parkHandOverLog, wrapper) < 1) {
                    log.error("----updateWorkStationFrom提示工作站更名失败");
                    return false;
                }
            }
        }
        //工作站实体的更新
        BeanUtils.copyProperties(parkWorkStationVo, workStation);
        workStation.setUpdateTime(new Date());
        if (!updateById(workStation)) {
            log.error("-----------updateWorkStationFrom提示工作站更新成功--------------------");
            return false;
        }
        //批量给当前工作站的车道都设置空
        String workStationId = workStation.getId();
        QueryWrapper<ParkArmInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("work_station_id", workStationId);
        List<ParkArmInfo> parkArmInfos = parkArmInfoService.list(wrapper);
        //为空说明该工作站第一次创建，且车道也没被绑定过
        if (ObjectUtil.isNotEmpty(parkArmInfos)) {
            //清除该工作站的原来所有车道
            for (ParkArmInfo parkArmInfo : parkArmInfos) {
                //车道都置为无人无工作站绑定的状态
                parkArmInfo.setWorkStationId("");
                parkArmInfo.setWorkStationName("");
                parkArmInfo.setUsedUserId("");
                if (!parkArmInfoService.updateEntity(parkArmInfo)) {
                    throw new Exception("车道置空失败");
                }
            }
        }
        //如果更新工作站时没选择任何车道
        if (ObjectUtil.isEmpty(parkWorkStationVo.getParkArmList())) {
            return true;
        }
        //如果更新工作站时选择了一些车道，则批量给车道设置工作站
        if (updateArms(parkWorkStationVo, workStation, workStation.getUsedUserId())) {
            return true;
        } else {
            log.error("------------updateWorkStationFrom提示车道绑定新工作站出错----------");
            throw new Exception("车道绑定新工作站时出错");
        }
    }

    /**
     * 删除工作站
     *
     * @param id 工作站id
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeWorkStationFrom(String id) throws Exception {
        //删除工作站
        this.removeById(id);
        //车道去除工作站属性
        QueryWrapper<ParkArmInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("work_station_id", id);
        List<ParkArmInfo> parkArmInfos = parkArmInfoService.list(wrapper);
        if (ObjectUtil.isEmpty(parkArmInfos)) {
            return true;
        }
        for (ParkArmInfo parkArmInfo : parkArmInfos) {
            parkArmInfo.setWorkStationName("");
            parkArmInfo.setWorkStationId("");
            parkArmInfo.setUsedUserId("");
            if (!parkArmInfoService.updateEntity(parkArmInfo)) {
                log.error("------removeWorkStationFrom提示更新车道失败---");
                throw new Exception("removeWorkStationFrom提示更新车道失败");
            }
        }
        return true;
    }

    /**
     * 批量删除工作站
     *
     * @param asList 工作站id
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeWorkStationFroms(List<String> asList) throws Exception {
        //删除工作站
        this.removeByIds(asList);
        log.info("-----------工作站批量删除成功--------------------");
        //车道批量去除工作站属性
        QueryWrapper<ParkArmInfo> wrapper = new QueryWrapper<>();
        for (String workId : asList) {
            wrapper.eq("work_station_id", workId);
            List<ParkArmInfo> parkArmInfos = parkArmInfoService.list(wrapper);
            for (ParkArmInfo parkArmInfo : parkArmInfos) {
                parkArmInfo.setWorkStationName("");
                parkArmInfo.setWorkStationId("");
                parkArmInfo.setUsedUserId("");
                if (!parkArmInfoService.updateEntity(parkArmInfo)) {
                    log.error("------removeWorkStationFroms提示更新车道失败---");
                    throw new Exception("removeWorkStationFroms提示更新车道失败");
                }
            }
        }
        log.info("-----------批量清除车道内工作站信息成功--------------------");
    }

    /**
     * 查询某个工作站
     *
     * @param id 工作站id
     * @return
     */
    @Override
    public ParkWorkStationVo getWorkStationFrom(String id) {
        ParkWorkStation workStation = this.getById(id);
        if (ObjectUtil.isEmpty(workStation)) {
            log.error("-----------------getWorkStationFrom提示未查询到工作站---------------");
            return null;
        }
        //拷贝属性
        ParkWorkStationVo parkWorkStationVo = new ParkWorkStationVo();
        BeanUtils.copyProperties(workStation, parkWorkStationVo);
        //获取车道信息并处理名字
        List<ParkArmInfo> objects = getParkArmInfos();
        parkWorkStationVo.setParkArmEntityList(objects);
        return parkWorkStationVo;
    }

    /**
     * 获取车道信息并处理名字
     *
     * @return
     */
    @Override
    public List<ParkArmInfo> getParkArmInfos() {
        //查询车道信息，包装成带从哪到哪，并且有些不可选的(有workid就不可选)
        List<ParkArmInfo> parkArmInfos = parkArmInfoService.list(new QueryWrapper<ParkArmInfo>().eq("arm_status", JddConstant.StringNumber.STRING_ONE));
        if (ObjectUtil.isEmpty(parkArmInfos)) {
            log.error("----------getParkArmInfos提示系统未找到车道信息或车道状态未启动-----------");
            return null;
        }
        //名字拼接用
        StringBuilder builder = new StringBuilder();
        List<ParkArmInfo> objects = parkArmInfos.stream().map(item -> {
            builder.setLength(0);
            builder.append(item.getArmName()).append("(");
            if (ObjectUtil.isNotEmpty(item.getSourceAreaId())) {
                ParkAreaInfo parkAreaInfo = parkAreaInfoMapper.selectById(item.getSourceAreaId());
                if (parkAreaInfo != null && parkAreaInfo.getAreaName() != null) {
                    builder.append(parkAreaInfo.getAreaName()).append("->");
                } else {
                    builder.append("区域配置错误,请检查->");
                }
            } else {
                builder.append("无->");
            }
            if (ObjectUtil.isNotEmpty(item.getTargetAreaId())) {
                ParkAreaInfo parkAreaInfo = parkAreaInfoMapper.selectById(item.getTargetAreaId());
                if (parkAreaInfo != null && parkAreaInfo.getAreaName() != null) {
                    builder.append(parkAreaInfo.getAreaName());
                } else {
                    builder.append("区域配置错误,请检查");
                }
            } else {
                builder.append("无");
            }
            builder.append(")");
            item.setArmName(builder.toString());
            return item;
        }).collect(Collectors.toList());
        return objects;
    }

    /**
     * 得到未使用得工作站信息
     *
     * @return 工作站信息
     */
    @Override
    public List<ParkWorkStation> noUseWorkStation() {
        //所有的工作站
        List<ParkWorkStation> list = this.list();
        if (ObjectUtil.isEmpty(list)) {
            log.error("------------noUseWorkStation提示未查询到工作站信息-----------------");
            return null;
        }
        //只查询离线
        return list.stream().filter(item -> JddConstant.StringNumber.STRING_ZERO.equals(item.getStatus())).collect(Collectors.toList());
    }

    /**
     * 岗亭登录后绑定工作站
     *
     * @param parkWorkStation 工作站
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> bindWorkStation(ParkWorkStation parkWorkStation) throws Exception {
        boolean createNewHandOverLogFlag = false;
        String stationId = parkWorkStation.getId();
        ParkWorkStation workStation = this.getById(stationId);
        //工作站为空
        if (ObjectUtil.isEmpty(workStation)) {
            log.error("---------bindWorkStation提示未找到工作站----------");
            return Result.error("未找到工作站");
        }
        //工作站操作员绑定
        LoginUser loginUser = LoginUserUtils.getLoginUser();
        //绑定前必须先登录
        if (ObjectUtil.isEmpty(loginUser)) {
            log.error("----------bindWorkStation提示请先登录！---------");
            return Result.error("请先登录");
        }
        if (ObjectUtil.isEmpty(loginUser.getUsername())) {
            log.error("----------bindWorkStation提示账户不可为空！---------");
            return Result.error("账户不可为空");
        }
        // 判断是否可以绑定
        // 状态是在线->不可以
//        if (JddConstant.StringNumber.STRING_ONE.equals(workStation.getStatus())) {
//            log.error("----------bindWorkStation提示工作站状态为在线------------");
//            return Result.error("请检查网络或刷新页面重试,或检查工作站是否已被人使用");
//        }
        //通过工作站id查车道,此操作前必须先在工作站绑定车道
        QueryWrapper<ParkArmInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("work_station_id", workStation.getId());
        List<ParkArmInfo> parkArmInfos = parkArmInfoService.list(queryWrapper);
        if (ObjectUtil.isEmpty(parkArmInfos)) {
            log.error("---------bindWorkStation提示工作站没选车道---------------");
            return Result.error("请先在工作站编辑处勾选要绑定的车道");
        }
        //判断车道是否全部都被禁用，如果全部都被禁用则没法进入监控
        List<ParkArmInfo> armInfoList = parkArmInfos.stream()
                .filter(item -> JddConstant.StringNumber.STRING_ONE.equals(item.getArmStatus()))
                .collect(Collectors.toList());
        if (ObjectUtil.isEmpty(armInfoList)) {
            log.error("---------bindWorkStation提示工作站的车道未启用---------------");
            return Result.error("工作站的车道未启用,请在车场信息的信息配置中启用");
        }
        //当前工作站是否有人绑定且非当前登录用户(如果有就自动交班)
        if (ObjectUtil.isNotEmpty(workStation.getOperationName()) && workStation.getOperationName().length() > 0) {
            QueryWrapper<ParkHandOverLog> wrapper = new QueryWrapper<>();
            wrapper.eq("work_name", workStation.getWorkName());
            wrapper.eq("operation_name", workStation.getOperationName());
            wrapper.isNull("hand_over_name");
            wrapper.orderByDesc("up_time");
            wrapper.last(" limit 1");
            ParkHandOverLog parkHandOverLog = parkHandOverLogMapper.selectOne(wrapper);

            if (null!=parkHandOverLog && !parkHandOverLog.getOperationName().equals(loginUser.getUsername())) {
                parkHandOverLog.setHandOverName(loginUser.getUsername());
                parkHandOverLog.setOverTime(new Date());
                parkHandOverLog.setSynchronousStatus("N");
                parkHandOverLog.setRemark("操作员切换，系统自动交班");
                parkHandOverLogMapper.updateById(parkHandOverLog);
                createNewHandOverLogFlag = true;
            }else {
                createNewHandOverLogFlag = true;
            }

        } else {
            createNewHandOverLogFlag = true;
        }

        //工作站操作员名字绑定
        workStation.setOperationName(loginUser.getUsername());
        workStation.setRealName(loginUser.getRealname());
        workStation.setUsedUserId(loginUser.getId());
        //写上上班时间
        workStation.setUpTime(DateUtil.formatDateTime(new Date()));
        //更新工作站
        if (!updateById(workStation)) {
            throw new Exception("更新工作站失败");
        }
        //车道绑定当前工作站得userid
        for (ParkArmInfo parkArmInfo : armInfoList) {
            //点击监控再取userId给车道，保证监控是该工作站选的车道
            parkArmInfo.setUsedUserId(loginUser.getId());
            parkArmInfo.setWorkStationId(workStation.getId());
            parkArmInfo.setWorkStationName(workStation.getWorkName());
            if (!parkArmInfoService.updateEntity(parkArmInfo)) {
                log.error("---------bindWorkStation提示更新车道时出错---------------");
                throw new Exception("更新车道失败");
            }
        }
        if (createNewHandOverLogFlag) {
            //生成一个交接班记录
            ParkHandOverLog parkHandOverLog = new ParkHandOverLog();
            //交接班记录拷贝属性从工作站
            BeanUtils.copyProperties(workStation, parkHandOverLog);
            parkHandOverLog.setId(null);
            parkHandOverLog.setUpTime(new Date());
            parkHandOverLog.setCreateTime(new Date());
            parkHandOverLog.setWorkName(workStation.getWorkName());
            parkHandOverLog.setOperationName(loginUser.getUsername());
            parkHandOverLog.setRealName(loginUser.getRealname());
            parkHandOverLog.setManualPaid(BigDecimal.ZERO);
            parkHandOverLog.setManualReceivable(BigDecimal.ZERO);
            parkHandOverLog.setManualDeduction(BigDecimal.ZERO);
            parkHandOverLog.setManualFree(BigDecimal.ZERO);
            parkHandOverLog.setOnlinePaid(BigDecimal.ZERO);
            parkHandOverLog.setOnlineDeduction(BigDecimal.ZERO);
            parkHandOverLog.setOnlineReceivable(BigDecimal.ZERO);
            parkHandOverLog.setOnlineFree(BigDecimal.ZERO);
            parkHandOverLog.setAbnormalOut(0);
            parkHandOverLog.setFreeOut(0);
            parkHandOverLog.setNormalNoFeeOut(0);
            parkHandOverLog.setNormalFeeOut(0);
            parkHandOverLog.setAllOutNum(0);
            parkHandOverLog.setRemark(null);
            if (parkHandOverLogMapper.insert(parkHandOverLog) < 1) {
                log.error("----bindWorkStation提示生成交接班记录失败---");
                throw new Exception("生成交接班记录失败");
            }
        }
        return Result.ok();
    }

    /**
     * 删除前查询状态
     *
     * @param id 主键
     * @return
     */
    @Override
    public boolean beforeDelete(String id) {
        ParkWorkStation workStation = this.getById(id);
        if (ObjectUtil.isEmpty(workStation)) {
            return false;
        }
        //如果当前工作站绑定了车道也不能删除
        QueryWrapper<ParkArmInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("work_station_id", workStation.getId());
        Integer count = parkArmInfoService.count(wrapper);
        if (count > 0) {
            log.error("------------beforeDelete提示有车道正在使用该工作站，无法删除该工作站----------");
            return false;
        }
        //状态如果是在线的就不能删除
        if (JddConstant.StringNumber.STRING_ONE.equals(workStation.getStatus())) {
            log.error("------------beforeDelete提示该工作站在线，无法删除----------");
            return false;
        }
        return true;

    }

    /**
     * 从车道信息查询工作站从而查询查询工作站得值班人
     *
     * @param parkArmInfo 车道信息
     * @return
     */
    @Override
    public String getStationOperationNameByParkArm(ParkArmInfo parkArmInfo) {
        if (ObjectUtil.isEmpty(parkArmInfo)) {
            log.error("-----------getStationOperationNameByParkArm提示参数为空！-------------");
            return null;
        }
        ParkWorkStation parkWorkStation = this.getById(parkArmInfo.getWorkStationId());
        if (ObjectUtil.isEmpty(parkWorkStation)) {
            log.error("-----------getStationOperationNameByParkArm提示车道没有绑定工作站！-------------");
            return null;
        }
        //所有岗亭的账户
        List<SysUser> gangtings = sysUserMapper.getGangTing();
        if (ObjectUtil.isEmpty(gangtings)) {
            log.error("-----------岗亭人员为空！-------------");
            return null;
        }
        //当前登录人账户是否在岗亭列表中
        for (SysUser gangting : gangtings) {
            if (ObjectUtil.isNotEmpty(gangting.getUsername())) {
                if (gangting.getUsername().equals(parkWorkStation.getOperationName())) {
                    return parkWorkStation.getOperationName();
                }
            }
        }
        return null;
    }


    /**
     * 功能描述:更新工作站得车道信息
     *
     * @param parkWorkStationVo 前端传来的工作站实体
     * @param workStation       工作站真正实体
     * @param userId            工作站原本的车道userId地址，添加时为空
     * @Author: lcy
     * @Date: 2021/12/8
     */
    public boolean updateArms(ParkWorkStationVo parkWorkStationVo, ParkWorkStation workStation, String userId) {
        //批量给车道设置工作站
        List<String> parkArmList = parkWorkStationVo.getParkArmList();
        if (ObjectUtil.isEmpty(parkArmList)) {
            return true;
        }
        for (String armId : parkArmList) {
            ParkArmInfo parkArmInfo = parkArmInfoService.getById(armId);
            if (ObjectUtil.isEmpty(parkArmInfo)) {
                log.error("-----------updateArms提示车道绑定工作站时车道信息不存在-------------");
                return false;
            }
            parkArmInfo.setWorkStationId(workStation.getId());
            parkArmInfo.setWorkStationName(workStation.getWorkName());
            //添加工作站时车道不设置userId地址，更新工作站时，新加或者更换的车道userId地址设置成工作站原来的车道userId地址
            parkArmInfo.setUsedUserId(userId);
            if (!parkArmInfoService.updateEntity(parkArmInfo)) {
                log.error("updateArms提示车道绑定新工作站时失败");
                return false;
            }
        }
        return true;
    }

    /**
     * 判断当前用户是否已经选过工作站
     *
     * @return
     * @throws Exception
     */
    @Override
    public boolean checkStationAuth() {
        LoginUser loginUser = LoginUserUtils.getLoginUser();
        if (ObjectUtil.isEmpty(loginUser)) {
            log.error("------------checkStationAuth提示当前没有用户登录-----------------");
            return false;
        }
        //拿当前登录人id去看有没有绑定工作站
        QueryWrapper<ParkWorkStation> wrapper = new QueryWrapper<>();
        wrapper.eq("used_user_id", loginUser.getId());
        List<ParkWorkStation> stations = this.list(wrapper);
        //没找到工作站说明没绑定
        if (ObjectUtil.isEmpty(stations)) {
            return false;
        }
        //找到工作站判断数据是否异常
        if (1 < stations.size()) {
            log.error("------------checkStationAuth提示当前用户有多个工作站,数据异常-----------------");
            return false;
        }
        return true;
    }

    /**
     * 设置workstation status为0
     *
     * @return
     */
    @Override
    public boolean initStationStatus() {
        return baseMapper.updateAllStatus(parkCode, JddConstant.StringNumber.STRING_ZERO);
    }

    /**
     * 岗亭登录后无需选择工作站
     *
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> bindWorkStationNoSelect() throws Exception {
        LoginUser loginUser = LoginUserUtils.getLoginUser();
        if (ObjectUtil.isEmpty(loginUser)) {
            log.error("---------bindWorkStationNoSelect提示loginUser为空----------");
            return Result.error("请检查网络后登录重试");
        }
        if (ObjectUtil.isEmpty(loginUser.getId())) {
            log.error("---------bindWorkStationNoSelect提示loginUser.getId()为空----------");
            return Result.error("请检查网络后登录重试");
        }
        String userId = loginUser.getId();
        QueryWrapper<ParkWorkStation> parkWorkStationQueryWrapper = new QueryWrapper<>();
        parkWorkStationQueryWrapper.eq("used_user_id", userId);
        parkWorkStationQueryWrapper.orderByDesc("up_time");
        parkWorkStationQueryWrapper.last(" limit 1");
        ParkWorkStation workStation = this.getOne(parkWorkStationQueryWrapper);
        //工作站为空
        if (ObjectUtil.isEmpty(workStation)) {
            log.error("---------bindWorkStationNoSelect提示未找到工作站----------");
            return Result.error("请检查网络后刷新重试");
        }
        //通过工作站id查车道,此操作前必须先在工作站绑定车道
        QueryWrapper<ParkArmInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("work_station_id", workStation.getId());
        List<ParkArmInfo> parkArmInfos = parkArmInfoService.list(queryWrapper);
        if (ObjectUtil.isEmpty(parkArmInfos)) {
            log.error("---------bindWorkStationNoSelect提示当前工作站尚未绑定车道---------------");
            return Result.error("请先在工作站编辑处勾选要绑定的车道");
        }
        //判断车道是否全部都被禁用，如果全部都被禁用则没法进入监控
        List<ParkArmInfo> armInfoList = parkArmInfos.stream()
                .filter(item -> JddConstant.StringNumber.STRING_ONE
                        .equals(item.getArmStatus())).collect(Collectors.toList());
        if (ObjectUtil.isEmpty(armInfoList)) {
            log.error("---------bindWorkStationNoSelect提示工作站的车道未启用---------------");
            return Result.error("工作站的车道未启用,请在车场信息的信息配置中启用");
        }
        //空值以及业务情况判断后对数据库操作
        workStation.setUsedUserId(userId);
        workStation.setOperationName(loginUser.getUsername());
        workStation.setRealName(loginUser.getRealname());
        updateById(workStation);
        //车道绑定当前工作站得userid
        for (ParkArmInfo parkArmInfo : armInfoList) {
            //点击监控再取userId给车道，保证监控是该工作站选的车道
            parkArmInfo.setUsedUserId(userId);
            parkArmInfo.setWorkStationName(workStation.getWorkName());
            parkArmInfo.setWorkStationId(workStation.getId());
            if (!parkArmInfoService.updateEntity(parkArmInfo)) {
                log.error("---------bindWorkStationNoSelect提示工作站的车道更新失败---------------");
                //回滚工作站更新
                throw new Exception("更新工作站失败");
            }
        }
        //未知情况下，已经绑定工作站的人却没有交接班记录
        QueryWrapper<ParkHandOverLog> wrapper = new QueryWrapper<>();
        wrapper.eq("operation_name", loginUser.getUsername());
        wrapper.isNull("hand_over_name");
        wrapper.orderByDesc("up_time");
        wrapper.last("limit 1");
        ParkHandOverLog handOverLog = parkHandOverLogMapper.selectOne(wrapper);
        if (ObjectUtil.isEmpty(handOverLog)) {
            ParkHandOverLog parkHandOverLog = new ParkHandOverLog();
            //交接班记录拷贝属性从工作站
            BeanUtils.copyProperties(workStation, parkHandOverLog);
            parkHandOverLog.setRemark("已绑定工作站用户无工作站,重新自动创建工作站");
            parkHandOverLog.setId(null);
            parkHandOverLog.setUpTime(new Date());
            parkHandOverLog.setCreateTime(new Date());
            parkHandOverLog.setOperationName(workStation.getOperationName());
            parkHandOverLog.setRealName(workStation.getRealName());
            parkHandOverLog.setManualPaid(BigDecimal.ZERO);
            parkHandOverLog.setManualReceivable(BigDecimal.ZERO);
            parkHandOverLog.setManualDeduction(BigDecimal.ZERO);
            parkHandOverLog.setManualFree(BigDecimal.ZERO);
            parkHandOverLog.setOnlinePaid(BigDecimal.ZERO);
            parkHandOverLog.setOnlineDeduction(BigDecimal.ZERO);
            parkHandOverLog.setOnlineReceivable(BigDecimal.ZERO);
            parkHandOverLog.setOnlineFree(BigDecimal.ZERO);
            parkHandOverLog.setAbnormalOut(0);
            parkHandOverLog.setFreeOut(0);
            parkHandOverLog.setNormalNoFeeOut(0);
            parkHandOverLog.setNormalFeeOut(0);
            parkHandOverLog.setAllOutNum(0);
            if (parkHandOverLogMapper.insert(parkHandOverLog) < 1) {
                log.error("---------bindWorkStationNoSelect提示已绑定工作站人员没交接班,自动创建交接班失败---------------");
                //回滚工作站更新
                throw new Exception("更新工作站时交接班创建时间");
            }
        }
        return Result.ok();
    }

    /**
     * 得到车场配置
     *
     * @return
     */
    public ConfigParkInfo getConfig() {
        return configParkInfoMapper.queryConfigParkInfo();
    }
}
